package com.zj.blockchain.util;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * @className: CryptoUtils
 * @description: TODO 类描述
 * @author: allnas
 * @date: 2020/2/29
 **/
@Slf4j
public final class CryptoUtils {
    /**
     * SHA256散列函数
     *
     * @param str
     * @return
     */
    @SneakyThrows
    public static String sha256(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(str.getBytes("UTF-8"));
        encodeStr = byte2Hex(messageDigest.digest());
        return encodeStr;
    }

    private static String byte2Hex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        String temp;
        for (int i = 0, size = bytes.length; i < size; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                builder.append("0");
            }
            builder.append(temp);
        }
        return builder.toString();
    }

    public static String md5(String str) {
        String resultStr = DigestUtils.md5DigestAsHex(str.getBytes());
        return resultStr.substring(4, resultStr.length());
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("\\-", "");
    }
}
